package com.ccl.iot.views;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ccl.iot.IOTInterface;
import com.ccl.iot.R;
import com.ccl.iot.bean.CodeviewBean;
import com.ccl.iot.device.IOTBLir;
import com.ccl.iot.device.IOTDevice;
import com.ccl.iot.device.IOTSubBLir;
import com.ccl.iot.dialogs.AddSubBLirDialog;
import com.ccl.iot.dvr.utils.CommonUtils;
import com.ccl.iot.ir.DBUtils;
import com.ccl.iot.publics.Messager;
import com.ccl.iot.publics.ThreadPoolUtils;
import com.ccl.iot.publics.UIUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cn.com.broadlink.sdk.BLLet;
import cn.com.broadlink.sdk.constants.controller.BLDeviceState;

/**
 * 创建者     王浩
 * 创建时间   2017/5/23 14:23
 * 描述	     博联设备的控制界面
 */

public class BLIrControlView extends LinearLayout {

    private LinearLayout mLlContainer;
    private ImageView mTvAdd;
    private TextView mTvCancel;
    private IOTBLir mDev;    //设备
    private Map<Long, SubBlirMiniView> mSubBlIrViews;
    private ArrayList<IOTSubBLir> mSubBlIrs;
    private SubBlirControlView mSubIrControlView;
    private SubBlirMiniView mTmpView;
    private View mOfflineMask;

    private boolean mSelectable;

    public BLIrControlView(Context context, boolean selectable) {
        this(context, null);
        mSelectable = selectable;
        mSubIrControlView.setCheckable(mSelectable);
    }

    public BLIrControlView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BLIrControlView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private IOTBLir.OnCodeChangedListener mOnCodeChangedListener = new IOTBLir.OnCodeChangedListener() {
        @Override
        public void onCodeChanged(final IOTSubBLir subBLir, CodeviewBean bean, final boolean isNew) {
            UIUtils.postTaskSafely(new Runnable() {
                @Override
                public void run() {
                    if (isNew) {
                        //有新的子设备
                        if (mTmpView != null) {
                            mLlContainer.removeView(mTmpView);
                            IOTSubBLir tmpDev = mTmpView.getSubBLir();
                            if (tmpDev != null) {
                                subBLir.setName(tmpDev.getName());
                            }
                            mTmpView = null;
                        }
                        SubBlirMiniView blirView = new SubBlirMiniView(getContext(), mSelectable);
                        blirView.setSubDev(subBLir);
                        blirView.setOnBlirClickListener(mBlirViewClickListener, mOnLongClickListener);
                        if (mSubBlIrViews == null) {
                            mSubBlIrViews = new HashMap<Long, SubBlirMiniView>();
                        }
                        mSubBlIrViews.put(subBLir.getSubId(), blirView);
                        mLlContainer.addView(blirView);
                        ImageView iv = blirView.getIvBlirView();
                        if (iv != null) {
                            iv.callOnClick();
                        }
                    } else {
                        //不是新设备, 更新UI
                        updateCurrectView();
                    }
                }
            });
        }

        @Override
        public void onSubDevDelete(final IOTSubBLir subBLir) {
            UIUtils.postTaskSafely(new Runnable() {
                @Override
                public void run() {
                    if (mSubBlIrViews != null && subBLir != null && mSubBlIrViews.size() > 0) {
                        SubBlirMiniView subBlirView = mSubBlIrViews.get(subBLir.getSubId());
                        if (subBlirView != null) {
                            mLlContainer.removeView(subBlirView);
                            if (mLlContainer.getChildCount() > 0) {
                                SubBlirMiniView childAt = (SubBlirMiniView) mLlContainer.getChildAt(0);
                                if (childAt != null) {
                                    ImageView ivBlirView = childAt.getIvBlirView();
                                    if (ivBlirView != null) {
                                        ivBlirView.callOnClick();
                                    }
                                }
                            } else {
                                mSubIrControlView.setVisibility(View.GONE);
                            }
                        }
                    }
                }
            });
        }
    };

    private void init() {
        View.inflate(getContext(), R.layout.view_ir_control, this);
        mLlContainer = (LinearLayout) findViewById(R.id.ll_irsubdev_container);
        mTvAdd = (ImageView) findViewById(R.id.tv_irsubdev_edit_add);
        mTvCancel = (TextView) findViewById(R.id.tv_irsubdev_edit_cancel);
        mSubIrControlView = (SubBlirControlView) findViewById(R.id.tl_irsubdev_control);
        mOfflineMask = findViewById(R.id.view_offline_mask_ir);

        mTvAdd.setOnClickListener(mBlirViewClickListener);
        mTvCancel.setOnClickListener(mBlirViewClickListener);

        //设置在线状态的监听器
        mSubIrControlView.setOnlineChangeListener(mOnlineChangeListener);

    }

    SubBlirControlView.OnDevOnlineChangeListener mOnlineChangeListener = new SubBlirControlView.OnDevOnlineChangeListener() {
        @Override
        public void onDevOnlineChange() {
            if (mDev != null) {
                //根据在线状态设置是否显示离线遮罩
                mOfflineMask.setVisibility(mDev.getRealOnline() ? View.GONE : View.VISIBLE);
            }
        }
    };

    /**
     * 设置红外设备, 并根据设备刷新UI
     *
     * @param dev
     */
    public void setDevice(IOTBLir dev) {
        //        if (mDev != dev) {
        if (mDev != null) {
            //删除ex设备的相关回调
            mDev.setOnCodeChangedListener(null);
            mDev.removeIconChangeListener(mIconChangeListener);
            mDev.removeNameChangeListener(mNameChangeListener);
        }

        //删除所有子设备的显示view
        mLlContainer.removeAllViews();
        if (mSubBlIrViews != null && mSubBlIrViews.size() > 0) {
            mSubBlIrViews.clear();
        }
        mDev = dev;
        if (mDev != null) {
            //检查在线状态
            checkOnline();
            //添加相关回调
            mDev.setOnCodeChangedListener(mOnCodeChangedListener);
            mDev.addIconChangeListener(mIconChangeListener);
            mDev.addNameChangeListener(mNameChangeListener);
            //获取子设备
            mSubBlIrs = mDev.getSubBLirs();
            if (mSubBlIrs != null && mSubBlIrs.size() > 0) {
                if (mSubBlIrViews == null) {
                    mSubBlIrViews = new HashMap<Long, SubBlirMiniView>();
                }
                for (IOTSubBLir subBLir : mSubBlIrs) {
                    //根据子设备创建view
                    SubBlirMiniView blirView = new SubBlirMiniView(getContext(), mSelectable);
                    blirView.setSubDev(subBLir);
                    blirView.setOnBlirClickListener(mBlirViewClickListener, mOnLongClickListener);
                    mSubBlIrViews.put(subBLir.getSubId(), blirView);
                    mLlContainer.addView(blirView);
                }

                SubBlirMiniView childAt = (SubBlirMiniView) mLlContainer.getChildAt(0);
                if (childAt != null) {
                    ImageView blirView = childAt.getIvBlirView();
                    if (blirView != null) {
                        //点击第一个子设备(更新UI)
                        blirView.callOnClick();
                    }
                }
            }
        }

        //        }
    }

    private void updateView() {
        setDevice(mDev);
    }

    private Runnable mUpdateViewTask = new Runnable() {
        @Override
        public void run() {
            updateView();
        }
    };

    private IOTInterface.IOTIconMonitorInterface.IOTIconChangeListener mIconChangeListener = new IOTInterface.IOTIconMonitorInterface.IOTIconChangeListener() {
        @Override
        public void onIconChanged(IOTDevice aSource, String aNewName) {
            UIUtils.postTaskSafely(mUpdateViewTask);
        }

    };

    private IOTInterface.IOTNameMonitorInterface.IOTNameChangeListener mNameChangeListener = new IOTInterface.IOTNameMonitorInterface.IOTNameChangeListener() {
        @Override
        public void onNameChanged(IOTDevice aSource, String aNewName) {
            UIUtils.postTaskSafely(mUpdateViewTask);
        }
    };

    //最后一次点击的子设备view
    private View lastSelectedView = null;
    private View.OnClickListener mBlirViewClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.iv_blirdev:
                    if (lastSelectedView != v) {
                        v.setSelected(true);
                        if (lastSelectedView != null) {
                            lastSelectedView.setSelected(false);
                        }
                        lastSelectedView = v;
                        //更新控制界面
                        updateCurrectView();
                    }
                    break;
                case R.id.iv_delete_blirdev:
                    final IOTSubBLir subDev = (IOTSubBLir) v.getTag();
                    if (subDev != null) {
                        ThreadPoolUtils.getInstance().addTask(new Runnable() {
                            @Override
                            public void run() {
                                String result = DBUtils.removeSubDevice(subDev.getDbId(), subDev.getSubId());
                                if ("OK".equals(result)) {
                                    Messager.Show(R.string.blir_dev_delete_success);
                                    subDev.delete();
                                } else {
                                    Messager.Show(R.string.blir_dev_delete_faild);
                                }
                            }
                        });
                    }
                    break;
                case R.id.tv_irsubdev_edit_cancel:
                    if (mSubBlIrViews != null && mSubBlIrViews.size() > 0) {
                        Set<Long> integers = mSubBlIrViews.keySet();
                        for (Long index : integers) {
                            mSubBlIrViews.get(index).updateView(ProbeView.STATE_NORMAL);
                        }
                    }

                    mTvCancel.setVisibility(View.GONE);
                    mTvAdd.setVisibility(View.VISIBLE);
                    break;
                case R.id.tv_irsubdev_edit_add:
                    AddSubBLirDialog dialog = new AddSubBLirDialog(getContext(), new AddSubBLirDialog.OnApplianceSelectListener() {
                        @Override
                        public IOTSubBLir onApplianceSelect(String type, String name) {
                            SubBlirMiniView blirView = new SubBlirMiniView(getContext(), mSelectable);
                            IOTSubBLir subBLir = new IOTSubBLir(type, name, mDev);
                            blirView.setSubDev(subBLir);
                            blirView.setOnBlirClickListener(mBlirViewClickListener, null);
                            if (mTmpView != null) {
                                mLlContainer.removeView(mTmpView);
                            }
                            mTmpView = blirView;
                            mLlContainer.addView(mTmpView);
                            blirView.callOnClick();
                            ImageView iv = blirView.getIvBlirView();
                            if (iv != null) {
                                iv.callOnClick();
                            }

                            return subBLir;
                        }

                        @Override
                        public IOTBLir getBlirDev() {
                            return mDev;
                        }
                    });

                    dialog.show();
                    break;
            }
        }
    };


    private View.OnLongClickListener mOnLongClickListener = new OnLongClickListener() {
        @Override
        public boolean onLongClick(final View v) {
            final String items[] = {getResources().getString(R.string.Rename), getResources().getString(R.string.blir_dev_delete), getResources().getString(R.string.blir_dev_batch_delete)};
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
            builder.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    if (which == 0) {
                        CommonUtils.removeDeviceDialog(getContext(), (IOTDevice) v.getTag());
                    } else if (which == 1) {
                        ThreadPoolUtils.getInstance().addTask(new Runnable() {
                            @Override
                            public void run() {
                                IOTSubBLir subDev = (IOTSubBLir) v.getTag();
                                if (subDev != null) {
                                    String result = DBUtils.removeSubDevice(subDev.getDbId(), subDev.getSubId());
                                    if ("OK".equals(result)) {
                                        Messager.Show(R.string.blir_dev_delete_success);
                                        subDev.delete();
                                    } else {
                                        Messager.Show(R.string.blir_dev_delete_faild);
                                    }
                                }else{
                                    Messager.Show(R.string.blir_dev_delete_faild);
                                }
                            }
                        });
                    } else {
                        if (mSubBlIrViews != null && mSubBlIrViews.size() > 0) {
                            Set<Long> integers = mSubBlIrViews.keySet();
                            for (Long index : integers) {
                                mSubBlIrViews.get(index).updateView(ProbeView.STATE_DELETE);
                            }
                        }
                        mTvCancel.setVisibility(View.VISIBLE);
                        mTvAdd.setVisibility(View.GONE);
                    }
                }
            });

            builder.show();
            return true;
        }
    };

    public void updateCurrectView() {
        //获取当前点击的view绑定的子设备
        IOTSubBLir subBLir = (IOTSubBLir) lastSelectedView.getTag();
        if (mSubIrControlView.getVisibility() != View.VISIBLE) {
            mSubIrControlView.setVisibility(View.VISIBLE);
        }
        mSubIrControlView.setIrSubDev(subBLir, false);
    }

    /**
     * 检查设备是否在线
     *
     * @return
     */
    private boolean checkOnline() {
        if (!mDev.getRealOnline()) {
            int state = BLLet.Controller.queryDeviceState(mDev.getDid());
            if (state == BLDeviceState.OFFLINE) {
                mOfflineMask.setVisibility(View.VISIBLE);
                mDev.setRealOnline(false);
                return false;
            }
            mDev.setRealOnline(true);
        }
        if (mOfflineMask.getVisibility() != View.GONE) {
            mOfflineMask.setVisibility(View.GONE);
        }
        return true;
    }
}
